<template>
  <a-modal
    title="新增权限审核配置"
    v-model="show"
    :maskClosable="false"
    :width="1050"
    placement="right"
    :closable="true"
    @cancel="onClose"
    :footer="null"
    :visiable="privilegeCheckAddVisiable"
  >
    <a-form :form="form">
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label="法人行号"
                       v-bind="formItemLayout"
                       :validateStatus="validateStatus"
                       :help="help"
                       style="display: block">
            <a-input v-decorator="['instId']" :disabled="true"/>
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label="id"
                       v-bind="formItemLayout"
                       :validateStatus="validateStatus"
                       :help="help" style="display: none">
            <a-input v-decorator="['id']"/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label="权限按钮名称"
                       v-bind="formItemLayout">
            <!--<a-select
              mode="default"
              :show-search="true"
              :allowClear="true"
              placeholder="请输入权限按钮名称"
              :default-active-first-option="false"
              :show-arrow="true"
              :filter-option="false"
              :not-found-content="null"
              @search="handlePermsSearch"
              style="width: 100%" v-decorator="['perms',{rules: [{ required: true, message: '请选择权限按钮' }]}]">
              <a-select-option v-for="r in menuData" :key="r.permission">{{r.text}} - {{r.permission}}</a-select-option>
            </a-select>-->
            <pagination-search-select v-decorator="['perms',{rules: [{ required: true, message: '请选择权限按钮' }]}]"
                                      :listUrl="getMenuListUrl"
                                      :listUrlParam="menuListUrlParam"
                                      valueName="perms"
                                      :showNameArr="showNameArr"
                                      :pageSize="10"
                                      :openSearch="true"
                                      :triggerChange="true"
                                      @change="permsSelectChange"
                                      @input="permsSelectChange"
                                      :searchWordKeyArr="searchWorldKey">

            </pagination-search-select>
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label="是否需要审核"
                       v-bind="formItemLayout">
            <a-select readOnly
                      mode="default"
                      :allowClear="true" @change="handleCheckedChange"
                      style="width: 100%" v-decorator="['checked',{rules: [{ required: true, message: '请选择是否需要审核' }]}]">
              <a-select-option key="Y">是</a-select-option>
              <a-select-option key="N">否</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label="审核层级"
                       v-bind="formItemLayout">
            <!--<a-input v-decorator="['checkLevel',{rules: [{required: true,max: 1,pattern: '^[1-9]+$' , message: '请输入审核层级，个位数字。' }]}]" :maxLength="1"/>-->


            <a-select readOnly
                      mode="default"
                      :allowClear="true"
                      style="width: 100%" v-decorator="['checkLevel',{rules: checkLevelRules}]">
              <a-select-option v-if="1<=maxCheckLevel" key="1">第一层级</a-select-option>
              <a-select-option v-if="2<=maxCheckLevel" key="2">第二层级</a-select-option>
              <a-select-option v-if="3<=maxCheckLevel" key="3">第三层级</a-select-option>
              <!--<a-select-option v-for="r in checkLevelData" :key="r.key">{{r.name}}</a-select-option>-->
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
        </a-col>
      </a-row>
      <a-row style="margin-bottom: 4em">
        <a-col :md="24" :sm="24">
          <a-form-item label='分配角色' :labelCol="{span: 3}" :wrapperCol="{span: 21}"
                       :validateStatus="menuSelectStatus"
                       :help="menuSelectHelp">
            <a-transfer
              :dataSource="roleDatas"
              show-search
              :list-style="{
            width: '350px',
            height: '350px',
          }"
              :operations="['to right', 'to left']"
              :targetKeys="targetRoleIds"
              :render="item => `${item.title}-${item.description}`"
              @change="handleChange"
            >
              <a-button
                slot="footer"
                slot-scope="props"
                size="small"
                style="float:right;margin: 5px"
                @click="getPrivilegeCheckRoles"
              >
                reload
              </a-button>
              <span slot="notFoundContent">
            没数据
          </span>
            </a-transfer>
          </a-form-item>
        </a-col>
        <!--<a-col :md="12" :sm="24">
        </a-col>-->
      </a-row>
    </a-form>
    <div class="drawer-bootom-button">
      <a-popconfirm title="确定放弃编辑？" @confirm="onClose" okText="确定" cancelText="取消">
        <a-button style="margin-right: .8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit" type="primary" :loading="loading">提交</a-button>
    </div>
  </a-modal>
</template>
<script>
    import PaginationSearchSelect from '@/components/select/PaginationSearchSelect'
    import {mapState} from "vuex"

    const formItemLayout = {
        labelCol: {span: 6},
        wrapperCol: {span: 18}
    }
    export default {
        name: 'PrivilegeCheckAdd',
        components: {
            PaginationSearchSelect
        },
        props: {
            privilegeCheckAddVisiable: {
                default: false
            },
            privilegeCheckData: {
                require: true
            },
            // menuData: {
            //     type: Array,
            //     default: () => []
            // },
            privilegeCheckInstId: {
                default: ""
            },
            maxCheckLevel:{
                default: "1"
            }
        },
      data() {
            return {
                getMenuListUrl:'admin/upmpmenu/permsPrivilegePageList',
                showNameArr:['menuName','perms'],
                menuListUrlParam:{'instId':this.privilegeCheckInstId,'type':'1','channelType':'00'},
                searchWorldKey:['menuName'],
                roleDatas: [],
                targetRoleIds: [],
                loading: false,
                formItemLayout,
                form: this.$form.createForm(this),
                validateStatus: '',
                help: '',
                menuSelectStatus: '',
                menuSelectHelp: '',
                privilegeCheck: {
                    menuId: ''
                },
                checkStrictly: false,
                checkLevelData:[],
                checkLevelRules:[{ required: true, message: '请选择审核层级' }]
            }
        },
        computed: {
            ...mapState({
                curruser: state => state.account.user
            }),
            show: {
                get: function () {
                    return this.privilegeCheckAddVisiable
                },
                set: function () {
                }
            }
        },
        /*mounted () {
            this.checkLevelData = [];
            for(let i=0;i<this.maxCheckLevel;i++){
                let checkLevel={};
                checkLevel.key=i+1;
                checkLevel.name="第"+checkLevel.key+"层级";
                this.checkLevelData.push(checkLevel);
            }
        },*/
        methods: {
            handleCheckedChange(val){
                // console.log('handleCheckedChange:'+val);
                // if(val=='N'){
                //     this.menuSelectStatus = ''
                //     this.menuSelectHelp = ''
                //     this.checkLevelRules = [{ required: false}]
                // }else{
                //     this.menuSelectStatus = ''
                //     this.menuSelectHelp = '请选择相应的权限'
                //     this.checkLevelRules = [{ required: true, message: '请选择审核层级' }]
                // }
            },
            permsSelectChange(val){
                console.log('permsSelectChange:'+val);
            },
            reset() {
                this.validateStatus = this.help = ''
                this.menuSelectStatus = this.menuSelectHelp = ''
                this.loading = false
                this.form.resetFields()
            },
            onClose() {
                this.reset()
                this.$emit('close')
            },
            handleCheck(checkedKeys) {
                this.checkedKeys = checkedKeys
                let checkedArr = Object.is(checkedKeys.checked, undefined) ? checkedKeys : checkedKeys.checked
                if (checkedArr.length) {
                    this.menuSelectStatus = ''
                    this.menuSelectHelp = ''
                } else {
                    this.menuSelectStatus = 'error'
                    this.menuSelectHelp = '请选择相应的权限'
                }
            },
            setFormValues({...privilegeCheck}) {
                let fields = ['instId', 'privilegeCheckCode', 'privilegeCheckName', 'privilegeCheckDesc']
                Object.keys(privilegeCheck).forEach((key) => {
                    if (fields.indexOf(key) !== -1) {
                        this.form.getFieldDecorator(key)
                        let obj = {}
                        obj[key] = privilegeCheck[key]
                        if(key=='instId'){
                            this.menuListUrlParam.instId = privilegeCheck[key];
                        }
                        this.form.setFieldsValue(obj)
                    }
                })
            },
            getPrivilegeCheckRoles() {
                this.form.getFieldDecorator("instId");
                this.form.setFieldsValue({"instId":this.privilegeCheckInstId})
                let privilegeCheck = this.form.getFieldsValue()
                privilegeCheck.instId = this.privilegeCheckInstId;
                privilegeCheck.channelType = '00'
                this.$get('admin/upmpprivilegecheck/getPrivilegeCheckRoles', {...privilegeCheck}).then((r) => {
                    let roleDataArr = [];
                    if(r.data.roleDatas){
                        for(var i=0;i<r.data.roleDatas.length;i++){
                            let roleData= {
                                key: "",
                                title: "",
                                description: "",
                                chosen: false
                            }
                            let remoteData = r.data.roleDatas[i];
                            roleData.key = remoteData.id
                            roleData.title = remoteData.roleName
                            roleData.description = remoteData.roleCode
                            if(r.data.targetRoleIds){
                              for(var j=0;j<r.data.targetRoleIds.length;j++){
                                  let targetRoleId = r.data.targetRoleIds[j];
                                  if(targetRoleId==remoteData.id){
                                      roleData.chosen = true;
                                      break;
                                  }
                              }
                            }
                            roleDataArr.push(roleData);
                        }
                    }
                    this.roleDatas = roleDataArr
                    this.targetRoleIds = r.data.targetRoleIds
                })
            },
            handleChange(targetRoleIds, direction, moveKeys) {
                console.log(targetRoleIds, direction, moveKeys);
                this.targetRoleIds = targetRoleIds;
                if (this.targetRoleIds.length > 0) {
                    this.menuSelectStatus = ''
                    this.menuSelectHelp = ''
                }
            },
            handleSubmit() {
                if (this.targetRoleIds.length === 0) {
                    this.menuSelectStatus = 'error'
                    this.menuSelectHelp = '请选择相应的角色'
                    this.loading = false
                } else {
                    this.form.validateFields((err, values) => {
                        if (!err) {
                            this.loading = true
                            let privilegeCheck = this.form.getFieldsValue()
                            // if (this.targetRoleIds.length === 0&&privilegeCheck.checked=='Y') {
                            // privilegeCheck.privilegeCheckId = this.privilegeCheckData.privilegeCheckId
                            privilegeCheck.roleId = this.targetRoleIds.join(',')
                            privilegeCheck.instId = this.privilegeCheckInstId
                            privilegeCheck.channelType = "00"
                            this.$post('admin/upmpprivilegecheck', {
                                ...privilegeCheck
                            }).then((r) => {
                                this.reset()
                                this.$emit('success')
                            }).catch(() => {
                                this.loading = false
                            })
                        }
                    })
                }
            }
        },
        watch: {
            privilegeCheckAddVisiable() {
                if (this.privilegeCheckAddVisiable) {
                    this.getPrivilegeCheckRoles()
                }
            }
        }
    }
</script>
